package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional
    @Override
    public void save(DishDTO dto) {
        //    菜品名称必须是唯一的
        Dish dish = dishMapper.getByName(dto.getName());
        if(null != dish)
            new RuntimeException("次菜名已经有了...");
//    菜品必须属于某个分类下，不能单独存在
//    每个菜品必须对应一张图片
//    插入菜品风味表
        dish = Dish.builder().build();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.save(dish);
        Long id = dish.getId();
        dto.getFlavors().forEach(dishFlavor -> {
            dishFlavor.setDishId(id);
            dishFlavorMapper.save(dishFlavor);
        });

        //清理radis缓存
        String redisKey = "dish_list_category_id" + dto.getCategoryId();
        redisTemplate.delete(redisKey);
    }

    @Override
    public @Validated PageResult page(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
//        根据页码展示菜品信息
//        每页展示10条数据
//        分页查询时可以根据需要输入菜品名称、菜品分类、菜品状态进行查询
        Page<Dish> page = dishMapper.page(dto);
        List<DishVO> vos = page.getResult().stream().map(dish -> {
            DishVO vo = new DishVO();
            BeanUtils.copyProperties(dish, vo);
            // 查询分类的名
            Category category = categoryMapper.get(dish.getCategoryId());
            vo.setCategoryName(category.getName());

            return vo;
        }).collect(Collectors.toList());

//        int size = page.size();
//
//        for (int i = 0; i < size; i++) {
//            System.out.println("aaa---"+vos.get(i).getUpdateTime());
//        }
//
//        for (int i = 0; i < size-1; i++) {
//            for (int i1 = 0; i1 < size-1-i; i1++) {
//                DishVO dishVO1 = vos.get(i1);
//                DishVO dishVO2 = vos.get(i1+1);
//                LocalDateTime updateTime1 = dishVO1.getUpdateTime();
//                LocalDateTime updateTime2 = dishVO2.getUpdateTime();
//                if(updateTime1.isAfter(updateTime2)){
//                    vos.set(i1, dishVO2);
//                    vos.set(i1+1, dishVO1);
//                }
//            }
//        }
//
//        for (int i = 0; i < size; i++) {
//            System.out.println("bbb---"+vos.get(i).getUpdateTime());
//        }

//        DishPageQueryDTO
//        DishVO
//        PageResult
        return PageResult.builder().total(page.getTotal()).records(vos).build();
    }

    @Transactional
    @Override
    public void dels(String[] split) {
//        可以一次删除一个菜品，也可以批量删除菜品
//        删除一个菜品和批量删除菜品共用一个接口
//        DeletionNotAllowedException
        List<Long> collect = Arrays.stream(split).map(s -> {
            long dishId = Long.parseLong(s);
//        起售中的菜品不能删除
            Dish dish = dishMapper.getById(dishId);
            if (1 == dish.getStatus())
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
//        被套餐关联的菜品不能删除
//        若删除的菜品数据关联着某个套餐，此时，删除失败。
//        setmeal_dish表为菜品和套餐关联的中间表。
            List<SetmealDish> sdList = setmealDishMapper.get(dishId);
            if (0 < sdList.size())
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
//        删除菜品后，关联的口味数据也需要删除掉
//        在dish表中删除菜品基本数据时，同时，也要把关联在dish_flavor表中的数据一块删除。
            dishMapper.del(dishId);
            dishFlavorMapper.delByDishId(dishId);

            return dish.getCategoryId();
        }).collect(Collectors.toList());

        collect.forEach(l->{
            clearRedis(l);
        });
    }

    @Override
    public DishVO info(String id) {
//        根据id查询菜品
        Long lid = Long.parseLong(id);
        Dish dish = dishMapper.getById(lid);
//        查不到抛异常
        if(null == dish)
            throw new RuntimeException("找不次菜品...");
        DishVO info = DishVO.builder().build();
        BeanUtils.copyProperties(dish, info);
//        查询菜品风味
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(lid);
        info.setFlavors(flavors);
        return info;
    }

    @Transactional
    @Override
    public void update(DishDTO dto) {
        Dish byId = dishMapper.getById(dto.getId());
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        //根据菜品id修改
        dishMapper.updateById(dish);
        updateStatus(dish.getId(), dish.getStatus());
        //菜品口味采用删除后添加
        dishFlavorMapper.delByDishId(dish.getId());
        dto.getFlavors().forEach(dishFlavor -> {
//            如果修改菜品前是没有菜品风味的，从前端的就没有菜品id
            if(null == dishFlavor.getDishId()){
                dishFlavor.setDishId(dish.getId());
            }
            dishFlavorMapper.save(dishFlavor);
        });
        //更新沉余字段
        setmealDishMapper.updateByDishId(SetmealDish.builder()
                .dishId(dish.getId())
                .name(dish.getName())
                .price(dish.getPrice())
                .build());
        clearRedis(byId.getCategoryId());
    }

    @Override
    public void updateStatus(long parseLong, int parseInt) {
        Dish byId = dishMapper.getById(parseLong);
//        完善套餐启售期间菜品不能禁售
        if(0==parseInt){
            List<SetmealDish> setmealDishList = setmealDishMapper.get(parseLong);
            for (SetmealDish setmealDish : setmealDishList) {
                Setmeal setmeal = setmealMapper.getById(setmealDish.getSetmealId());
                if(1 == setmeal.getStatus())
                    throw new RuntimeException(setmeal.getName()+"套餐启售中，无法禁售...");
            }
        }
        dishMapper.updateById(Dish.builder().id(parseLong).status(parseInt).build());
        clearRedis(byId.getCategoryId());
    }

    @Override
    public List<DishVO> listByCategoryIdOrName(Long categoryId, String name) {
        List<Dish> dishList = null;
        if(null != categoryId)
            dishList = dishMapper.getByCategoryId(categoryId);
        else if(null != name)
            dishList = dishMapper.getListByName(name);
        return dishList.stream().map(dish -> {
            DishVO vo = new DishVO();
            BeanUtils.copyProperties(dish, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getByDishCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    public void clearRedis(Long categoryId){
        String redisKey1 = "dish_list_category_id" + categoryId;
        String redisKey2 = "setmeal_list_category_id" + categoryId;
        if(redisTemplate.hasKey(redisKey1))
            redisTemplate.delete(redisKey1);
        if(redisTemplate.hasKey(redisKey2))
            redisTemplate.delete(redisKey2);
    }
}